import json
from flask import Flask, render_template, request, redirect, session, jsonify
from home.bar import highest_wind_humidity
from home.biaoqian import count_weather
from home.line import highest_lowest_temperature
from lishi.search import search_weather
from map.utils import city_tem
from search.line import line
from search.table import table
from userUtils.query import query

app = Flask(__name__)

# 设置密钥Flask 的会话对象（session）用于在用户与服务器的交互过程中存储和跟踪特定于用户的数据。
# 例如，当用户成功登录后，将用户的邮箱存储在会话中，以便在后续的请求中识别用户身份，实现用户在不同页面之间的无缝切换而无需重复登录。
app.secret_key = 'your_secret_key'


@app.route('/')
def every():
    return render_template('login.html')


@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        request.form = dict(request.form) #字典格式

        email = request.form.get('email')
        password = request.form.get('password')    #获取用户输入的

        user = query('SELECT * FROM users WHERE email = %s AND password = %s', [email, password], 'select_one')
        #查找数据
        if user:
            session['email'] = email
            return redirect('/home', 301)
        ## 如果找到匹配的用户记录，将用户邮箱存储在会话中，并重定向到 '/home' 路由。
        else:
            error_message = '账号或密码错误'
            return render_template('login.html', error_message=error_message)

    else:
        return render_template('login.html')


@app.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        request.form = dict(request.form)
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        password_checked = request.form.get('passwordChecked')
        # 从表单中获取用户输入的用户名、邮箱、密码和确认密码。
        if password != password_checked:
            error_message = '两次密码不符'
            return render_template('register.html', error_message=error_message)

        email_exists = query('SELECT * FROM users WHERE email = %s', [email], 'select_one')
        if email_exists:
            error_message = '该邮箱已被注册'
            return render_template('register.html', error_message=error_message)
        # 检查输入的邮箱是否已经在数据库中存在，如果存在，返回 register.html 模板并传递错误消息。
        user_exists = query('SELECT * FROM users WHERE username = %s', [username], 'select_one')
        if user_exists:
            error_message = '用户名已被注册'
            return render_template('register.html', error_message=error_message)

        query('INSERT INTO users (username, email, password) VALUES (%s, %s, %s)', [username, email, password])
        # 如果用户名和邮箱都未被注册且密码一致，将用户信息插入到数据库的 users 表中。
        session['email'] = email
        return redirect('/login', 301)
        # 将用户邮箱存储在会话中，并重定向到 '/login' 路由
    else:
        return render_template('register.html')


@app.route("/home")   #首页
def home():
    # 获取用户信息
    email = session.get('email')
    # 四个标签
    sunny, cloudy, rainy, snowy = count_weather()    #从home.biaoqian中引入
    # 折线图
    highest_temperatures, lowest_temperatures = highest_lowest_temperature()  #从home.line中引入的

    # 饼图和环形图
    highest_wind, highest_humidity = highest_wind_humidity()      #home.bar中引入

    #Flask 应用中用于渲染并返回home.html，并传递了变量
    return render_template('home.html',
                           email=email,
                           # 标签
                           sunny=sunny,
                           cloudy=cloudy,
                           rainy=rainy,
                           snowy=snowy,
                           # 折线图
                           highest_temperatures=highest_temperatures,
                           lowest_temperatures=lowest_temperatures,
                           # 饼图和环形图
                           highest_wind=highest_wind,
                           highest_humidity=highest_humidity
                           )


# 天气地图路由
@app.route('/map')
def map():
    # 获取用户信息
    email = session.get('email')
    temperature = city_tem()
    temperature = json.dumps(temperature)  # 将温度数据转换为 JSON 格式
    return render_template('map.html',
                           email=email,
                           temperatureData=temperature
                           )


@app.route('/search', methods=['POST', 'GET'])
def search():
    email = session.get('email')
    try:
        if request.method == 'POST':
            # 接收参数
            city = request.form.get('city')

            # 调用 line 函数获取四个不同的天气指标数据
            line_result = line(city)

            # 调用 table 函数获取天气数据表格
            table_result = table(city)

            # 将四个指标数据分别赋值给不同的变量
            highest, lowest, visibility, humidity = line_result

            # 将结果组织成字典
            search_result = {
                'highest': highest,
                'lowest': lowest,
                'visibility': visibility,
                'humidity': humidity,
                'table_result': table_result  # 将新查询的结果添加到字典中
            }
            # print("查询结果:", search_result)
            return jsonify(search_result)
        return render_template('search.html', email=email)
    except Exception as e:
        error_message = "存在错误: {}".format(str(e))
        return jsonify({"error": error_message}), 500


@app.route('/lishi', methods=['POST', 'GET'])
def lishi():
    email = session.get('email')
    try:
        if request.method == 'POST':
            city = request.form.get('city')
            date = request.form.get('date')  # 接收日期参数
            search_result = search_weather(city, date)
            return jsonify(search_result)
        return render_template('lishi.html', email=email)
    except Exception as e:
        error_message = "存在错误: {}".format(str(e))
        return jsonify({"error": error_message}), 500


if __name__ == '__main__':
    app.run(debug=True)
